package com.handpay.nocardpay.baselibrary.main.all.view.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.handpay.nocardpay.baselibrary.R;
import com.handpay.nocardpay.baselibrary.commbase.BaseProtocolKey;
import com.handpay.nocardpay.baselibrary.commbase.view.fragment.BaseFragment;
import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.config.SecureManager;
import com.handpay.nocardpay.baselibrary.db.ormlite.DataBaseComponentModel;
import com.handpay.nocardpay.baselibrary.raindrops.RainDropsFragment;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.BannerByChannelBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentItemBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentMappingItemBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.ComponentRelationItemBean;
import com.handpay.nocardpay.baselibrary.main.all.model.bean.component.http.ComponentHttpBean;
import com.handpay.nocardpay.baselibrary.main.all.presenter.BannerPresenterImpl;
import com.handpay.nocardpay.baselibrary.main.all.presenter.CustomComponentPresenterImpl;
import com.handpay.nocardpay.baselibrary.main.all.view.IAllView;
import com.handpay.nocardpay.baselibrary.main.all.view.widget.FunctionInfo;
import com.handpay.nocardpay.baselibrary.main.all.view.widget.FunctionOnItemClickListener;
import com.handpay.nocardpay.baselibrary.main.all.view.widget.GlideImageLoader;
import com.handpay.nocardpay.baselibrary.main.all.view.widget.IconBaseAdapter;
import com.handpay.nocardpay.baselibrary.main.home.model.bean.LowestAccountTransferAmount;
import com.handpay.nocardpay.baselibrary.main.home.model.bean.PaymentTypeListBean;
import com.handpay.nocardpay.baselibrary.main.home.presenter.LowestPresenterImpl;
import com.handpay.nocardpay.baselibrary.main.home.view.IHomeView;
import com.handpay.nocardpay.baselibrary.main.mine.MainFragment;
import com.handpay.nocardpay.baselibrary.onlinemarket.view.fragment.OnlineMarketFragment;
import com.handpay.nocardpay.baselibrary.pay.unipay.view.fragment.ShowHTMLFragment;
import com.handpay.nocardpay.baselibrary.smartrepayment.SmartRePayFragment;
import com.handpay.nocardpay.baselibrary.utils.AccountUtils;
import com.handpay.nocardpay.baselibrary.utils.ClientEngine;
import com.handpay.nocardpay.baselibrary.utils.CommonUtils;
import com.handpay.nocardpay.baselibrary.utils.DialogUtils;
import com.handpay.nocardpay.baselibrary.utils.NoCardPayConstant;
import com.handpay.nocardpay.baselibrary.utils.PreferenceManager;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lyang on 2018/2/2.
 */

public class AllFragment extends BaseFragment implements IAllView, IHomeView {
    private BannerPresenterImpl mBannerPresenterImpl;
    private Banner mBanner;
    public static String EXTERNAL_HTML = "0";
    public static String INTERNAL_HTML = "1";
    public static String INTERNAL_APP = "3";
    private ArrayList<String> mComponentData = null;
    private GridView all_function_gv;
    private IconBaseAdapter mIconBaseAdapter;
    private FunctionOnItemClickListener mIconBaseOnItemClickListener;
    private DataBaseComponentModel mDBModel;
    private LowestPresenterImpl mLowestPresenter;
    private CustomComponentPresenterImpl mCustomComponentPresenterImpl;

    private LowestAccountTransferAmount mLowestAccountTransferAmount;
    private double MIN_AMOUNT = 1000;

    public static AllFragment newInstance() {
        Bundle args = new Bundle();
        AllFragment fragment = new AllFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_main_all;
    }

    @Override
    public void initView(View view) {
        mBanner = (Banner) view.findViewById(R.id.banner);
        mBanner.setImageLoader(new GlideImageLoader());
        all_function_gv = (GridView) view.findViewById(R.id.all_function_gv);
        mIconBaseAdapter = new IconBaseAdapter(_mActivity);
        all_function_gv.setAdapter(mIconBaseAdapter);
        mIconBaseOnItemClickListener = new FunctionOnItemClickListener(_mActivity) {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String tag = ((IconBaseAdapter) parent.getAdapter()).getData().get(position);
                HPLog.i(HPLog.YL_TAG, "onItemClick:" + tag);
                gridViewItemOnclick(tag);
            }
        };

        all_function_gv.setOnItemClickListener(mIconBaseOnItemClickListener);
    }


    public void gridViewItemOnclick(String tag) {
        HashMap<String, FunctionInfo> maps = FunctionInfo.getFunctionInfos(_mActivity);
        FunctionInfo info = maps.get(tag);
        HPLog.i(HPLog.YL_TAG, "gridViewItemOnclick:" + info.toString());
        if (tag.equalsIgnoreCase(FunctionInfo.HONG_SHOP_CODE)) {
            if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.NOUPLOAD) {
//                DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.home_online_market_no_submit_qualification), _mActivity.getString(R.string.home_online_market_dialog_cancel), true);


                DialogUtils.showAlertDialog(_mActivity, getString(R.string.dialog_title), _mActivity.getString(R.string.home_online_market_no_submit_qualification), false, getString(R.string.home_online_market_dialog_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            } else {
                String host;
                host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = NoCardPayConfig.ONLINE_MARKET_URL;
                }
                String mallUrl = host + "?merchantCode=" + AccountUtils.getMerchantCode(_mActivity);
                double minAmount = MIN_AMOUNT;
                if (mLowestAccountTransferAmount != null) {
                    minAmount = mLowestAccountTransferAmount.getUnionPayOnlineAmount();
                }
                ((MainFragment) getParentFragment()).start(OnlineMarketFragment.newInstance(minAmount, mallUrl));
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.INTRE_PAYMENT_CODE)) {//智能还款
            if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
                String host;
                host = mDBModel.queryComponent(info.itemId).getItemUrl();
                if (TextUtils.isEmpty(host)) {
                    host = NoCardPayConfig.SMARTPAY_URL;
                }
                ((MainFragment) getParentFragment()).start(SmartRePayFragment.newInstance(host));
            } else {
//                DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.home_smart_re_pay_no_success_qualification), _mActivity.getString(R.string.home_online_market_dialog_cancel), true);
                DialogUtils.showAlertDialog(_mActivity, getString(R.string.dialog_title), _mActivity.getString(R.string.home_smart_re_pay_no_success_qualification), false, getString(R.string.home_online_market_dialog_cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
            }
        } else if (tag.equalsIgnoreCase(FunctionInfo.LOAN_CODE)) {//智能还款
            String host = mDBModel.queryComponent(info.itemId).getItemUrl();
            if (TextUtils.isEmpty(host)) {
                host = "https://www.handmart.cn/web/loan/banners.html";
            }

            ((MainFragment) getParentFragment()).start(ShowHTMLFragment.newInstance(_mActivity.getString(R.string.loan_title), host));
        } else if (tag.equalsIgnoreCase(FunctionInfo.DFPAY_ITEM_CODE)) {
            if (AccountUtils.getAccountStatus(_mActivity) == AccountUtils.AccountStatus.SUCCESS) {
                //用户首次进入贷款需提示
                boolean isAgreeRainDrops = PreferenceManager.getInstance(_mActivity).getBoolean("RainDrops_"+ AccountUtils.getAccountPhone(_mActivity), false);
                if (!isAgreeRainDrops) {
                    DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.hint_raindrops), _mActivity.getString(R.string.dialog_appay), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ((MainFragment) getParentFragment()).start(RainDropsFragment.newInstance());
                        }
                    }, _mActivity.getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                } else {
                    ((MainFragment) getParentFragment()).start(RainDropsFragment.newInstance());
                }
            } else {
                DialogUtils.showAlertDialog(_mActivity, _mActivity.getString(R.string.dialog_title), _mActivity.getString(R.string.home_dfpay_no_success_qualification), false);
            }
        }
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mBannerPresenterImpl = new BannerPresenterImpl(this, _mActivity);
        mCustomComponentPresenterImpl = new CustomComponentPresenterImpl(this, _mActivity);
        mLowestPresenter = new LowestPresenterImpl(this, _mActivity);
        mComponentData = new ArrayList<String>();
        mDBModel = new DataBaseComponentModel(_mActivity);
        getBannerChannel();
        queryLowestAmount();
        queryCustomComponentItem();
    }

    private void getBannerChannel() {
        HashMap<String, Object> paramers = new HashMap<String, Object>();
        paramers.put(BaseProtocolKey.CLIENTCHANNEL, ClientEngine.getInstance().CLIENTCHANNEL);
        paramers.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
        paramers.put("showTab", "01");
        mBannerPresenterImpl.getBannerByChannel(paramers, BannerByChannelBean.class, false);
    }

    @Override
    public void setBannerByChannel(final BannerByChannelBean response) {
        HPLog.i(HPLog.YL_TAG, "setBannerByChannel:" + response.toString());
        mBanner.setImages(response.getList());
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                BannerByChannelBean.ListBean info = response.getList().get(position);
                if (INTERNAL_HTML.equals(info.getBannerLinkType()) || EXTERNAL_HTML.equals(info.getBannerLinkType())) {
                    String title = info.getLinkTitle() == null ? "" : info.getLinkTitle();
                    String url = info.getBannerLink();
                    ((MainFragment) getParentFragment()).start(ShowHTMLFragment.newInstance(title, url));
                } else if (INTERNAL_APP.equals(info.getBannerLinkType())) {
//                    mIconBaseOnItemClickListener.gridViewItemOnclick(info.getContentUrl());
                }
            }
        });
        mBanner.start();
    }

    @Override
    public void setCustomComponent(ComponentHttpBean response) {
        DataBaseComponentModel model = new DataBaseComponentModel(_mActivity);
        List<ComponentHttpBean.ListBeanX> listX = response.getList();
        HPLog.i(HPLog.YL_TAG, "组件 listX.size():" + listX.size());
        if (listX.size() == 0) {
            doShowComponentItem();
            return;
        }
        boolean bDelShowArea1 = false;
        boolean bDelShowArea2 = false;
        boolean bDelShowArea3 = false;
        for (ComponentHttpBean.ListBeanX beanX : listX) {
            String iconName = SecureManager.getInstance().des(beanX.getIconName(), 0, null);
            String itemCode = SecureManager.getInstance().des(beanX.getItemCode(), 0, null);
            String itemTitle = SecureManager.getInstance().des(beanX.getItemTitle(), 0, null);
            String itemUrl = SecureManager.getInstance().des(beanX.getItemUrl(), 0, null);
            String itemType = String.valueOf(beanX.getItemType());
            if (TextUtils.isEmpty(itemCode)) {
                //如果itemCode返回空放弃这次请求
                return;
            }
            int orderNum = beanX.getOrderNum();
            String parentId = String.valueOf(beanX.getParentId());
            String showArea = String.valueOf(beanX.getShowArea());
            String updateTime = String.valueOf(System.currentTimeMillis());

            ComponentMappingItemBean componentMappingItemBean = new ComponentMappingItemBean();
            if (bDelShowArea1 == false && showArea.equals("1")) {
                bDelShowArea1 = true;
                model.deleteComponentMappingByShowArea("1");
            }
            if (bDelShowArea2 == false && showArea.equals("2")) {
                bDelShowArea2 = true;
                model.deleteComponentMappingByShowArea("2");
            }
            if (bDelShowArea3 == false && showArea.equals("3")) {
                bDelShowArea3 = true;
                model.deleteComponentMappingByShowArea("3");
            }
            if (itemType.equals("2") && beanX.getList().size() != 0) {
                model.deleteComponentRelationByParentId(itemCode);
            }
            componentMappingItemBean.setOrderNum(orderNum);
            componentMappingItemBean.setItemCode(itemCode);
            componentMappingItemBean.setShowArea(showArea);
            componentMappingItemBean.setUpdateTime(updateTime);
            HPLog.i(HPLog.YL_TAG, "组件Mapping添加componentMappingItemBean:" + componentMappingItemBean.toString());
            model.addComponentMapping(componentMappingItemBean);

            ComponentItemBean componentItemBean = new ComponentItemBean();
            componentItemBean.setItemCode(itemCode);
            componentItemBean.setItemTitle(itemTitle);
            componentItemBean.setItemUrl(itemUrl);
            componentItemBean.setItemType(itemType);
            componentItemBean.setIconName(iconName);
            componentItemBean.setUpdateTime(updateTime);

            HPLog.i(HPLog.YL_TAG, "组件 添加componentItemBean:" + componentItemBean.toString());
            model.addComponent(componentItemBean);
            List<ComponentHttpBean.ListBeanX.ListBean> list = beanX.getList();
            for (ComponentHttpBean.ListBeanX.ListBean bean : list) {
                String sIconName = SecureManager.getInstance().des(bean.getIconName(), 0, null);
                String sItemCode = SecureManager.getInstance().des(bean.getItemCode(), 0, null);
                String sItemTitle = SecureManager.getInstance().des(bean.getItemTitle(), 0, null);
                String sItemUrl = SecureManager.getInstance().des(bean.getItemUrl(), 0, null);
                String sItemType = String.valueOf(bean.getItemType());
                String sOrderNum = String.valueOf(bean.getOrderNum());
                ComponentRelationItemBean componentRelationItemBean = new ComponentRelationItemBean();
                componentRelationItemBean.setItemCode(sItemCode);
                componentRelationItemBean.setOrderNum(sOrderNum);
                componentRelationItemBean.setParentItemCode(itemCode);
                model.addComponentRelation(componentRelationItemBean);
                HPLog.i(HPLog.YL_TAG, "组件关系componentRelationItemBean:" + componentRelationItemBean.toString());
                ComponentItemBean subComponentItemBean = new ComponentItemBean();
                subComponentItemBean.setItemCode(sItemCode);
                subComponentItemBean.setItemTitle(sItemTitle);
                subComponentItemBean.setItemUrl(sItemUrl);
                subComponentItemBean.setItemType(sItemType);
                subComponentItemBean.setIconName(sIconName);
                subComponentItemBean.setUpdateTime(updateTime);
                HPLog.i(HPLog.YL_TAG, "组件添加subComponentItemBean:" + subComponentItemBean.toString());
                model.addComponent(subComponentItemBean);
            }
        }
        doShowComponentItem();
    }

    private void queryLowestAmount() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("version", ClientEngine.getInstance().VERSION);
        params.put("platform", ClientEngine.getInstance().MOBILE_TYPE);
        params.put("channel", ClientEngine.getInstance().CHANNEL);
        mLowestPresenter.getLowestAccountTransferAmount(params, LowestAccountTransferAmount.class, false);
    }

    private void queryCustomComponentItem() {

        int POLL_TIME = CommonUtils.objectToInt(ClientEngine.getInstance().getGlobal(NoCardPayConstant.POLL_TIME, 60 * 10));
        DataBaseComponentModel dbModel = new DataBaseComponentModel(_mActivity);
        ComponentItemBean bean = dbModel.queryComponentList().get(0);
        String updateTime = "0";
        if (bean != null) {
            updateTime = bean.getUpdateTime();
        }
        HPLog.i(HPLog.YL_TAG, "组件当前时间：" + System.currentTimeMillis() + ":" + stampToDate(System.currentTimeMillis()));
        HPLog.i(HPLog.YL_TAG, "组件最后入库时间：" + updateTime + ":" + stampToDate(Long.valueOf(updateTime).longValue()));
        HPLog.i(HPLog.YL_TAG, "组件需要更新时间：" + (Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000)) + ":" + stampToDate(Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000)));
        if (Long.valueOf(updateTime) == 0 || System.currentTimeMillis() > (Long.valueOf(updateTime).longValue() + (POLL_TIME * 60 * 1000))) {
            HPLog.i(HPLog.YL_TAG, "组件更新：");

            HashMap<String, Object> params = new HashMap<String, Object>();
            params.put(BaseProtocolKey.CHANNEL, ClientEngine.getInstance().CHANNEL);
            params.put(BaseProtocolKey.CLIENTCHANNEL, ClientEngine.getInstance().CLIENTCHANNEL);
            mCustomComponentPresenterImpl.getCustomComponent(params, ComponentHttpBean.class, false);
        } else {
            HPLog.i(HPLog.YL_TAG, "组件不更新：");
            doShowComponentItem();
        }
    }

    public static String stampToDate(long lt) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    private void doShowComponentItem() {
        try {
            mComponentData.clear();
            DataBaseComponentModel dbModel = new DataBaseComponentModel(_mActivity);
            List<ComponentMappingItemBean> list = dbModel.queryComponentMappingByShowArea("1");
            for (ComponentMappingItemBean bean : list) {
                HPLog.i(HPLog.YL_TAG, "componentMappingItemBean show:" + bean.toString());
                mComponentData.add(bean.getItemCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            mComponentData.clear();
        }
        mIconBaseAdapter.setData(mComponentData);
    }

    @Override
    public void setLowestAccountTransferAmount(LowestAccountTransferAmount response) {
        mLowestAccountTransferAmount = response;

    }

    @Override
    public void setPaymentTypeList(PaymentTypeListBean response) {

    }
}
